import axios from "axios";
import qs from "qs";

const config = {
  baseURL: "https://sms.yunpian.com/v2/",
  apikey: process.env.SMS_YP_KEY,
};

export async function sendSms(mobile, text, opts = {}) {
  const apikey = opts.apikey || config.apikey;
  const body = {
    apikey,
    mobile,
    text,
    extend: opts.extend,
  };
  try {
    const { data } = await axios.post(
      config.baseURL + "sms/single_send.json",
      qs.stringify(body)
    );
    // console.log(data)
    return { code: 0, msg: "已发送", detail: data.sid };
  } catch (error) {
    let { data, status = -1 } = error.response || {};
    // console.log(e.response)
    if (typeof data == "string" || !data)
      data = {
        code: status,
        msg: `网络错误(${status})`,
        detail: error.message,
      };
    return data;
  }
}
